package main

import (
	"context"
	"github.com/grpc-ecosystem/grpc-gateway/runtime"
	"google.golang.org/grpc"
	"net/http"
	"os"
	gw "week13/api/proto"
	"week13/configs"
	"week13/errors"
	"week13/log"
)
//后台API网关
func run() error {
	var err error
	dir := "C:\\Users\\03\\Desktop\\training-camp\\week13\\configs\\json\\app.json"
	f, err := os.Open(dir)
	if err !=nil {
		panic(err)
	}
	defer f.Close()
	appConfigs := configs.LoadAppConfigs(f)

	ctx := context.Background()
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	mux := runtime.NewServeMux()
	opts := []grpc.DialOption{grpc.WithInsecure()}
	//鉴权服务
	if _,ok := appConfigs["auth"];!ok {
		return errors.NewCommonError(1,"Auth server config err")
	}
	err = gw.RegisterAuthSrvHandlerFromEndpoint(ctx, mux, appConfigs["auth"].Addr, opts)
	if err != nil {
		return err
	}
	//运营后台服务
	if _,ok := appConfigs["admin"];!ok {
		return errors.NewCommonError(1,"Auth server config err")
	}
	err = gw.RegisterAdminSrvHandlerFromEndpoint(ctx, mux, appConfigs["admin"].Addr, opts)
	if err != nil {
		return err
	}

	log.Info("admin 服务开启")
	if _,ok := appConfigs["adminServer"];!ok {
		cancel()
		return errors.NewCommonError(1,"adminServer server config err")
	}
	return http.ListenAndServe(appConfigs["adminServer"].Addr, mux)
}
func main() {
	if err := run(); err != nil {
		log.Fatal("admin server start",err.Error())
	}
}